/**
 * Module dependencies.
 */

var express = require('express');
var routes = require('./routes');
var MongoStore = require("connect-mongo")(express);
var settings = require('./settings');
var crypto = require('crypto');
var User = require('./models/user.js');
var Post = require('./models/post.js');
var flash = require('connect-flash');

var app = express();

// Configuration

app.configure(function(){
  app.set('views', __dirname + '/views');
  var partials = require('express-partials');
  app.set('view engine', 'ejs');
  app.use(partials());
  app.use(flash());
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(express.cookieParser()); 
  app.use(express.session({ 
    secret: settings.cookieSecret, 
    store: new MongoStore({ 
      db: settings.db 
    }) 
  })); 
  //这一段一定要放到session后面，否则会出现user不存在的错误
  app.use(function(req, res, next){
      res.locals.user = req.session.user;
      res.locals.error = req.flash('error');
      res.locals.success = req.flash('success');
      next();
  });
  app.use(app.router);
  app.use(express.static(__dirname + '/public'));
});

app.configure('development', function(){
  app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

app.configure('production', function(){
  app.use(express.errorHandler());
});

app.get('/',routes.index);
app.get('/hello', routes.hello);
app.get('/user/:username', function(req,res){
  res.send('user:'+ req.params.username);
});
app.get('/reg', function(req,res){
  res.render('reg',{
    title:'用户注册',
  });
});

app.post('/reg', function(req,res){
  if(req.body['password-repeat'] != req.body['password']){
    req.flash('error','两次输入的口令不一致');
    return res.redirect('/reg');
  }
  var md5 = crypto.createHash('md5');
  var password = md5.update(req.body.password).digest('base64');

  console.log(req.body.username);
  console.log(req.body.password);

  var newUser = new User({
    name: req.body.username,
    password: password,
  });

  User.get(newUser.name,function(err,user){
    if(user){
      err = 'username already exists.';
    }
    if(err){
      req.flash('error',err);
      return res.redirect('/reg');
    }
    newUser.save(function(err) {
        if (err) {
          req.flash('error', err);
          return res.redirect('/reg');
        }
        req.session.user = newUser;
        req.flash('success', '註冊成功');
        res.redirect('/');
    });
  });

});

app.get("/login",function(req,res){
  res.render("login",{title:"用户登录"});
});

app.post("/login", function(req,res){
  var md5 = crypto.createHash('md5');
  var password = md5.update(req.body.password).digest('base64');

  User.get(req.body.username, function(err, user){
    console.log(req.body.username);
    if(!user){
      req.flash('error','用户不存在');
      return res.redirect('/login');
    }
    if(user.password != password){
      req.flash('error','用户口令错误!');
      return res.redirect('/login');
    }
    req.session.user = user;
    req.flash('success', req.body.username+'登入成功');
    res.redirect('/');
  });
});

app.get('/logout', function(req, res){
  req.session.user = null;
  req.flash('success', '登出成功');
  res.redirect('/');
});

app.post('/post', function(req,res){
  var currentUser = req.session.user;
  var post = new Post(currentUser.name,req.body.post);
  post.save(function(err){
    if(err){
      req.flash('error',err);
      return res.redirect('/');
    }
    req.flash('success','发表成功');
    res.redirect('/u/'+currentUser.name);
  });
});

app.get('/u/:user', function(req,res){
  User.get(req.params.user, function(err,user){
     if(!user){
        req.flash('error','用户不存在');
        return res.redirect('/');
     }
     Post.get(user.name, function(err,posts){
        if(err){
          req.flash('error',err);
          return res.redirect('/');
        }
        console.log(posts);
        res.render('user',{
          title:user.name,
          posts:posts
        });
     });
  });
});

app.listen(3000);
